﻿using Ekton_Manage_IBusiness;
using Ekton_Manage_InfrastructureCore.Common;
using Hangfire;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Ekton_Manage_Web.Extensions.ApplicationBuilderExtensions
{
    public class TimeJobMiddleware
    {
        private RequestDelegate _next;
        private readonly IJobBusiness _jobBusiness;

        public TimeJobMiddleware(RequestDelegate requestDelegate,
            IJobBusiness jobBusiness)
        {
            this._next = requestDelegate;
            _jobBusiness = jobBusiness;
        }

        public Task Invoke(HttpContext context)
        {
            if (!Const.firstinto)
            {
                Task.Run(() => RecurringJob.AddOrUpdate(() => _jobBusiness.Run(), Cron.MinuteInterval(1)));
                Task.Run(() => RecurringJob.AddOrUpdate(() => _jobBusiness.SecondRun(), Cron.MinuteInterval(1)));
                Task.Run(() => RecurringJob.AddOrUpdate(() => _jobBusiness.SendEmail(), Cron.MinuteInterval(1)));
                Task.Run(() => RecurringJob.AddOrUpdate(() => _jobBusiness.SendSysMsg(), Cron.MinuteInterval(1)));
                //Task.Run(() => RecurringJob.AddOrUpdate(() => _jobBusiness.SendEmailByQueue(), Cron.MinuteInterval(20)));
                Const.firstinto = true;
            }
            return _next(context);
        }
    }
}
